package components.resultLayer
{
	import Classes.CLoader;
	import Classes.pi_TransparentJPG;
	
	import SEApp.se_util;
	
	import UIFree.ObjectEvent;
	import UIFree.controls.uif_button;
	import UIFree.controls.uif_label;
	import UIFree.controls.uif_maskedArea;
	import UIFree.uif_component;
	
	import UIUtils.uif_util;
	import UIUtils.uif_utilBitmap;
	
	import classes.clt_events;
	
	import components.clt_component;
	import components.photo.clt_photoEditor;
	
	import data.clt_data;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.geom.Matrix;
	import flash.geom.Point;
	import flash.geom.Rectangle;

	public class clt_editLayer extends clt_component {
		private var _display	: clt_resultBitmap;
		private var _curFocus	: clt_elemBitmap;
		private var _dragPos	: Point;
		private var _focusBmp	: clt_selectedBmp;
		private var _focusLayer	: uif_maskedArea;
		private var _help		: uif_label;
		private var _nlthelp	: uif_label;
		
		public function clt_editLayer(parent:uif_component, ax:int=0, ay:int=0, awidth:int=0, aheight:int=0) {
			super(parent, ax, ay, awidth, aheight, styleClass);
			var inner: Rectangle = getInner();
			
			_display = new clt_resultBitmap(this, new BitmapData(inner.height, inner.height, false, 0xFFFF00));
			_display.x = inner.x + (inner.width - _display.width) / 2;
			_display.y = inner.y;
			_focusLayer = new uif_maskedArea(this, _display.x, _display.y, _display.width, _display.height);
			_focusBmp = new clt_selectedBmp(_focusLayer);
			
			_help = new uif_button(this, _display.x + _display.width - 180, inner.y, 180, 50, 'help');
			_help.text = clt.classes.locale.EDITORHELP;
			_help.setVisibility(false);
			
			_nlthelp = new uif_button(this, _display.x + (_display.width - 180) / 2, inner.y + inner.height - se_util.DEFHEIGHTBUTTON, 180, se_util.DEFHEIGHTBUTTON, 'button');
			_nlthelp.text = clt.classes.locale.NOLINKTEXTHELP;
			_nlthelp.setVisibility(false);
			_nlthelp.addEvent(MouseEvent.CLICK, doNoLinkButton);
		}
		
		protected function doOver(e: MouseEvent): void {
			addEvent(MouseEvent.MOUSE_MOVE, doMove);
		}
		
		protected function doOut(e: MouseEvent): void {
			removeEventListener(MouseEvent.MOUSE_MOVE, doMove);
			if (_curFocus) unfocus();
			visibleNoLinkTextHelp(false);
		}
		
		protected function get editing(): Boolean {
			return _dragPos != null;
		}
		
		protected function get displayMPos(): Point {
			return new Point(display.mouseX, display.mouseY);
		}
		
		protected function doDown(e: MouseEvent): void {
			_dragPos = new Point(e.stageX, e.stageY);
			if (_curFocus) {
				if (e.ctrlKey) {
					var p: Point = PointToElem(_curFocus, displayMPos);
					_curFocus._data.corr = [p.x, p.y];
					clt.workspace.dispatchEvent(new Event(clt_events.DISPLAYREFRESH));
				}
				_display.traceUpdateElement(_curFocus._data);
			}
		}
		
		protected function PointToElem(elem: clt_elemBitmap, p : Point): Point {
			var mat: Matrix = elem.transform.matrix.clone();
			mat.invert();
			p = mat.transformPoint(p);
			p.x = Math.round(p.x);
			p.y = Math.round(p.y);
			return p;
		}
		
		protected function doUp(e: MouseEvent): void {
			_dragPos = null;
		}
		
		protected function getHit(): clt_elemBitmap {
			var list: Array = new Array();
			display.forEach(function(elem: Object, elemName: String): void {
				list.push(elemName);
			});
			
			for (var i: int=list.length-1; i>=0; i--) {
				var elem: clt_elemBitmap = display.getElem(list[i]); 
				if (elem) {
					if (elem.bitmapData.hitTest(new Point(0, 0), 0x80, 
							PointToElem(elem, displayMPos))) {
						return elem;
					}
				}
			}
			return null;
		}
		
		protected function doMove(e: MouseEvent): void {
			if (clt.sitedata.TEXTFROMRESULT && !clt.user.noLinkText && _display.linkTextRect(getInner()).containsPoint(mousePos))
				visibleNoLinkTextHelp(true);
				
			if (!editing) {
				var hit: clt_elemBitmap = getHit();
				if (hit) {
					if (_curFocus != hit) focus(hit);
					return;
				}
				if (_curFocus) unfocus();
			} else if (_curFocus) {
				var curPos	: Point = new Point(e.stageX, e.stageY);
				var moveTo	: Point = _dragPos.subtract(curPos);
				if (e.shiftKey) {
					display.resetElemEars(_curFocus, null, 1 + moveTo.y / 100);
				} else {
					display.resetElemEars(_curFocus, moveTo);
				}
				
				updateFocusBmp();
				
//				display.dispatchEvent(new Event(clt_events.DISPLAYREFRESH));
				_dragPos = curPos;
			}
		}
		
		protected function doNoLinkButton(e: Event): void {
			clt.alert(clt.classes.locale.WARNING, clt.sitedata.NOLINKTEXTDESC, function(): void {
				clt.workspace.dispatchEvent(new Event(clt_events.NOLINKTEXTRELEASE));
			}, true);
		}
		
		protected function visibleNoLinkTextHelp(a_show: Boolean): void {
			_nlthelp.slideVisible(a_show);
		}
		
		protected function focus(a_elem: clt_elemBitmap): void {
			_curFocus = a_elem;
//			if (_focusBmp.bitmapData) _focusBmp.bitmapData.dispose();
			_focusBmp.bitmapData = _curFocus.bitmapData.clone();
			_focusBmp.visible = true;
			updateFocusBmp();
			_help.slideShow();
		}
		
		protected function updateFocusBmp(): void {
			if (display.maskInfo) {
				_focusBmp.transform.matrix = _curFocus.getMatrix(display.maskInfo, display.getFaceRect(), display.scaleFromMask());
			}
		}
		
		protected function unfocus(): void {
			_curFocus = null;
			if (_focusBmp.bitmapData) _focusBmp.bitmapData.dispose();
			_focusBmp.visible = false;
			_help.slideHide();
		}
		
		override protected function listenEvents():void {
			addEvent(MouseEvent.ROLL_OVER, doOver);
			addEvent(MouseEvent.ROLL_OUT, doOut);
			addEvent(MouseEvent.MOUSE_DOWN, doDown);
			addEvent(MouseEvent.MOUSE_UP, doUp);
			
			addEvent(clt_events.UPDATECUTOUT, doUpdateCutout, workspace);
			addEvent(clt_events.UPDATEPHOTO, doUpdatePhoto, workspace);
			addEvent(clt_events.SELECTHAIR, doUpdateHair, workspace);
			addEvent(clt_events.SELECTCLOTH, doUpdateCloth, workspace);
			addEvent(clt_events.SELECTBACKGROUND, doUpdateBackground, workspace);
			addEvent(clt_events.AUTOCORRECTION, doAutoCorrection, workspace);
			addEvent(clt_events.MANUALCORR, doManualCorrection, workspace);
			addEvent(clt_events.STANDARTCORR, doStandartCorrection, workspace);
			addEvent(clt_events.LOADBACKGROUND, doLoadBackground, workspace);
		}
		
		protected function doManualCorrection(e: ObjectEvent): void {
			display.manualCorr = e.object as Array;
		}
		
		protected function doStandartCorrection(e: ObjectEvent): void {
			display.standartCorr = e.object as Array;
		}
		
		protected function doAutoCorrection(e: ObjectEvent): void {
			display.autocorrection = e.object as Boolean;
		}
		
		protected function doUpdatePhoto(e: ObjectEvent): void {
			var bmd: BitmapData = (e.object as clt_photoEditor).clipBitmap;
			workspace.dispatchEvent(new ObjectEvent(clt_events.UPDATEFACE, bmd));
			bmd.dispose();
//			display.updateFace((e.object as clt_photoEditor).clipBitmap);
		}
		
		protected function doUpdateCutout(e: Event): void {
			display.updateCutout(workspace.maskInfo);
		}
		
		protected function doUpdateHair(e: ObjectEvent): void {
			clt.addElementJPGTmpl('hair', clt_servers.HAIR_URL + 'JPG/' + e.object.id, e.object);
/*			
			pi_TransparentJPG.load(clt_servers.HAIR_URL + 'JPG/' + e.object.id + clt_data.JPGEXT,
									clt_servers.HAIR_URL + 'JPG/' + e.object.id + 'm' + clt_data.JPGEXT,
									app, function(_jpgBitmap: Bitmap, bmdMask: BitmapData): void {
				_jpgBitmap.smoothing = true;
				workspace.dispatchEvent(new ObjectEvent(clt_events.SETELEMENT, {
					name	: 'hair',
					bmp		: _jpgBitmap,
					data	: e.object
				}));
				bmdMask.dispose();
			});
*/			
		}
		
		protected function doUpdateBackground(e: ObjectEvent): void {
			var ld: CLoader = new CLoader(null, clt_servers.BACKGROUND_URL + e.object.id + clt_data.JPGEXT, function(e: Event): void {
				display.updateBackground(se_util.bmpCopy(ld));
				ld.unload();
			})
		}
		
		protected function doLoadBackground(e: ObjectEvent): void {
/*			var loader	: Loader = e.object as Loader;
			var bmp		: Bitmap = new Bitmap(new BitmapData(600, 600, false));
			var rect	: Rectangle = uif_util.EnterHere(new Rectangle(0, 0, bmp.width, bmp.height), new Point(loader.width, loader.height), false);
			var scale	: Point = new Point(rect.width/loader.width, rect.height/loader.height);
			var mat		: Matrix = new Matrix(1, 0, 0, 1, rect.x, rect.y);
			mat.scale(scale.x, scale.y);
			bmp.bitmapData.draw(loader, mat, null, null, null, true);
			display.updateBackground(bmp);
*/			
			display.updateBackground(new Bitmap(uif_utilBitmap.copyBitmapData(e.object as Loader)));
		}
		
		protected function doUpdateCloth(e: ObjectEvent): void {
			clt.addElementJPGTmpl('cloth', clt_servers.CLOTH_URL + 'JPG/' + e.object.id, e.object, function(): void {
				workspace.id = e.object.ws;
			});
		}
		
		public function get display(): clt_resultBitmap {
			return _display;
		}	
	}
}